<template>
  <div class="app-container">
    <el-row>
      <el-col>
        <el-button type="primary" @click="handleNewtask()">新建任务</el-button>
        <el-button type="danger" @click="handleDel()">删除任务</el-button>
        <el-input v-model="input" placeholder="请输入内容" class="search"><el-button slot="append" icon="el-icon-search" /></el-input>
      </el-col>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @selection-change="handleSelectionChange"
      @select-all="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="40"
        align="center"
      />
      <el-table-column label="序号" width="50" prop="Id" align="center" />
      <el-table-column label="数据集" prop="DatasetName" align="center" />
      <el-table-column label="算法版本" prop="VersionName" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.Status | statusFilter">
            <i :class="row.Status | statusIconFilter" />
            {{ row.Status | statusTextFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160" prop="CreateTime" align="center" />
      <el-table-column label="操作"  align="center" width="300">
        <template slot-scope="{row}">
          <el-button type="primary" size="medium" @click="handleAnalysis(row)">分析</el-button>
          <el-button type="primary" size="medium" @click="handleReport(row)">报告</el-button>
          <el-button type="danger" size="medium">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-row>
      <el-col :span="4" style="padding-top: 27px">
        <el-button type="primary" @click="handleReport">多选报告</el-button>
      </el-col>
      <pagination v-show="total>0" :total="total" :page.sync="taskQuery.Page" :limit.sync="taskQuery.Size" style="text-align:right" @pagination="getList" />
    </el-row>

    <el-dialog :visible.sync="dialogNewtask" width="60%">
      <el-form
        ref="dataForm"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="数据集" prop="DatasetId">
          <el-dropdown trigger="click" style="width:100%" placement="bottom" :hide-on-click="false" @visible-change="changeValue($event)">
            <el-button id="drodownbox" class="small-dropdown">
              <span v-for="(name, index) of showDatasetName" :key="index" class="dropdown-checked">{{ name }}<i class="el-icon-close delete-dataset" @mousedown="handleDelDataset($event, index)" /></span>
              <span v-if="showDatasetName.length === 0" class="dropdown-checked dropdown-checked_no">请选择数据集</span>
              <!-- <span :style="{color: showDatasetName? '#333': '#bbb'}">{{ showDatasetName || '请选择数据集' }}</span> -->
              <i :class="datasetDropdown? 'el-icon-arrow-up':'el-icon-arrow-down'" style="position:absolute; right: 10px; top: 10px; color: #bbb" />
            </el-button>
            <el-dropdown-menu slot="dropdown" ref="mydropd" :append-to-body="false">
              <div style="width: 300px; font-size: 14px; color: #999;padding: 0 10px 10px 10px">
                <span>来源</span>
                <select v-model="fromSelected" class="small-select" @change="selectChange()">
                  <option value="">请选择</option>
                  <option v-for="(item, index) of fromArray" :key="index" :value="item">{{ item }}</option>
                </select>
                <span>，分类</span>
                <select v-model="classSelected" class="small-select" @change="selectChange()">
                  <option value="">请选择</option>
                  <option v-for="(item, index) of classArray" :key="index" :value="item">{{ item }}</option>
                </select>
              </div>
              <div v-for="(item, index) of DataSetList" :key="index" :command="item.Id" :class="item.active? 'small-dropdown_active':''" class="small-dropdown_item" @mousedown="handleCommand(item.Id)">
                <el-row>
                  <el-col :span="22">
                    {{ item.Name }}
                  </el-col>
                  <el-col :span="2">
                    <i class="el-icon-check small-dropdown_active_icon" />
                  </el-col>
                </el-row>
              </div>
            </el-dropdown-menu>
          </el-dropdown>
          <div id="here" ref="here" />
        </el-form-item>
        <el-form-item label="算法版本" prop="Version">
          <el-select
            v-model="temp.Version"
            class="filter-item"
            multiple
            placeholder="请选择"
            style="width: 300px; overflow:hidden"
          >
            <el-option
              v-for="item of editionOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogNewtask = false">取消</el-button>
        <el-button type="primary" @click="createData()">确定</el-button>
      </div>

      <!-- <div class="lastDialog">
        <el-dialog
          title=""
          :visible.sync="dialogVisible"
          width="40%"
          :before-close="handleClose">
          <span>这是一段信息</span>
          <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
          </span>
        </el-dialog>
      </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { fetchVersionList, CreateCronTask, fetchGetDataSetList, DataSetClassAndFrom } from '@/api/video'
import { fetchTaskList } from '@/api/task'
import { mapGetters } from 'vuex'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '',
        '1': '',
        '2': '',
        '3': 'info',
        '4': 'success',
        '-1': 'danger'
      }
      return statusMap[status]
    },
    statusIconFilter(status) {
      const statusMap = {
        '0': 'el-icon-check',
        '-1': 'el-icon-close'
      }
      return statusMap[status]
    },
    statusTextFilter(status) {
      const statusMap = {
        '0': '创建完成',
        '1': '评测执行',
        '2': '预测完成',
        '3': '评测标注',
        '4': '评测完成',
        '-1': '任务出错'
      }
      return statusMap[status]
    },
    formatTypeFilter(status) {
      const statusMap = {
        '0': '视频类型',
        '1': '图片类型',
        '2': '文本类型'
      }
      return statusMap[status]
    },
    categoryTypeFilter(status) {
      const statusMap = {
        '-1': '无',
        '0': '低俗审核',
        '1': '内容识别',
        '2': '智能识别',
        '3': '智能推荐',
        '4': '优质挖掘'
      }
      return statusMap[status]
    }
  },
  components: { Pagination },
  data() {
    return {
      className: '微信看一看',
      fromName: 'ugc',
      fromSelected: '',
      classSelected: '',
      classArray: [],
      fromArray: [],
      input: '',
      list: null,
      total: 0,
      listLoading: true,
      multipleSelection: [],
      datasetDropdown: false,
      showDatasetName: [],
      DataSetList: [],
      dialogNewtask: false,
      editionOptions: [],
      taskQuery: {
        Page: 1,
        Size: 10,
        SdkId: -1
      },
      temp: {
        Class: '',
        CronStr: '',
        DatasetId: '',
        From: '',
        Name: '',
        Type: 1,
        Version: []
      },
    }
  },
  computed: {
    ...mapGetters(['ProjectId']),
    watchProjectId() {
      return this.$store.state.constants.ProjectId
    }
  },
  watch: {
    watchProjectId(curVal, oldVal) {
      this.getList()
    }
  },
  created() {
    this.getList()
    this.fetchGetDataSetList()
    this.DataSetClassAndFrom()
  },
  methods: {
    DataSetClassAndFrom() {
      DataSetClassAndFrom().then(response => {
        this.classArray = response.Data[0].Class
        this.fromArray = response.Data[0].From
      })
    },
    selectChange() {
      this.fetchGetDataSetList()
    },
    changeValue(e) {
      this.datasetDropdown = e
    },
    handleCommand(command) {
      const data = this.DataSetList.filter(item => Number(item.Id) === Number(command))
      if (data[0].active) {
        this.showDatasetName = this.showDatasetName.filter(item => item !== data[0].Name)
        let dataset = this.temp.DatasetId.split(',')
        dataset = dataset.filter(item => item !== String(data[0].Id))
        this.temp.DatasetId = dataset.join()
        this.DataSetList = this.DataSetList.map(item => {
          if (item.Id === data[0].Id) {
            item.active = false
          }
          return item
        })
      } else {
        this.showDatasetName.push(data[0].Name)
        this.temp.DatasetId = this.temp.DatasetId ? this.temp.DatasetId + ',' + data[0].Id : String(data[0].Id)
        this.DataSetList = this.DataSetList.map(item => {
          if (item.Id === data[0].Id) {
            item.active = true
          }
          return item
        })
      }

      this.$nextTick(() => {
        this.hereTop = this.$refs.here.getBoundingClientRect().top
        // this.$refs.here.firstElementChild.style.top = +this.hereTop + 'px'
      })
    },
    fetchGetDataSetList() {
      fetchGetDataSetList({
        From: this.fromSelected,
        Class: this.classSelected,
        SdkId: -1,
        Page: 1,
        Size: 100
      }).then(response => {
        const showDatasetName = []
        const DatasetId = this.temp.DatasetId.split(',')
        this.DataSetList = response.Data.map(imap => {
          if (DatasetId.indexOf(String(imap.Id)) !== -1) {
            showDatasetName.push(imap.Name)
            imap.active = true
          } else {
            imap.active = false
          }
          return imap
        })
        this.showDatasetName = showDatasetName
      })
    },
    getList(page, id) {
      if (!this.ProjectId) return
      this.listLoading = true
      const params = {
        ...this.taskQuery,
        ProjectId: id || this.ProjectId
      }
      fetchTaskList(params).then(response => {
        this.list = response.Data
        this.total = response.Count

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.5 * 1000)
      }).catch(() => {
        this.listLoading = false
      })
    },
    fetchVersionList() {
      const params = {
        ProjectId: -1,
        SdkId: -1
      }
      return new Promise(resolve => {
        fetchVersionList(params).then(response => {
          const editionOptions = []
          response.Data.map(item => {
            if (item.Status === 0) {
              editionOptions.push({
                value: item.VersionId,
                label: item.SdkName.trim().concat('_', item.Version)
              })
            }
          })
          this.editionOptions = editionOptions
          resolve()
        })
      })
    },
    handleNewtask() {
      this.dialogNewtask = true
      this.temp = {
        Class: '',
        CronStr: '',
        DatasetId: '',
        From: '',
        Name: '',
        Type: 1,
        Version: []
      }
      this.$nextTick(() => {
        this.fetchVersionList()
      })
    },
    handleDel(){
      this.$alert("是否删除当前文件？",{
        confirmButtonText:'确认',
         cancelButtonText:'取消'
      }).then(()=>{
        this.$alert("删除成功",{
          iconClass:"el-icon-success",
          center:true
        })
      }).catch(()=>{
        this.$alert("已取消删除")
      })
    },
    dialogNewtask(){
      this.$alert('已取消新建')
    },
    handleChangeType(val) {
      this.temp.DatasetId = ''
      this.showDatasetName.length = 0
      this.$nextTick(() => {
        this.$refs.here.appendChild(
          this.$refs.mydropd.popperElm
        )
      })
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      console.log(val)
    },
    createData() {
      const params = {
        ...this.temp,
        ProjectID: Number(this.ProjectId)
      }
      params.Version = params.Version.map(item => {
        const itemObj = {}
        this.editionOptions.forEach(ieach => {
          if (item === Number(ieach.value)) {
            itemObj.VersionId = String(ieach.value)
            itemObj.VersionName = ieach.label
          }
        })
        return itemObj
      })
      params.Type = Number(params.Type)
      params.DatasetId = String(params.DatasetId)
      CreateCronTask(params).then(response => {
        this.$refs.dataForm.resetFields()
        this.dialogNewtask = false
        this.getList()
      })
      this.dialogNewtask = false
      this.$alert("新建/修改成功",{
          iconClass:"el-icon-success",
          center:true
        })
    },

    dialogNewtask(){
      this.dialogNewtask = true;
      this.$alert("已取消新建")
    },
    handleClose(done){
      this.$confirm('确认关闭?')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    handleDelDataset(e, idx) {
      const oE = e || event
      oE.stopPropagation()
      let datasetName = ''
      this.showDatasetName = this.showDatasetName.filter((item, index) => {
        if (idx === index) {
          datasetName = item
        } else {
          return item
        }
      })
      let datasetId = ''
      this.DataSetList = this.DataSetList.map(item => {
        if (item.Name === datasetName) {
          datasetId = item.Id
          item.active = false
        }
        return item
      })
      let dataset = this.temp.DatasetId.split(',')
      dataset = dataset.filter(item => item !== String(datasetId))
      this.temp.DatasetId = dataset.join()
      this.$nextTick(() => {
        this.hereTop = this.$refs.here.getBoundingClientRect().top
        // this.$refs.here.firstElementChild.style.top = +this.hereTop + 'px'
      })
    },
    handleAnalysis(row) {
      if (row.Status < 3) return this.$message.error('预测进行中')
      const params = {
        ReportKey: row.ReportKey,
        HasLabel: row.HasLabel,
        InputType: row.InputType,
        OutputType: row.OutputType,
        version: row.VersionId,
        name: row.VersionName,
        taskname: row.TaskName,
        Projectid: this.ProjectId
      }
      sessionStorage.setItem('SET_TASK', JSON.stringify(params))
      this.$router.push({ path: '/taskList/list/analysis', query: { id: row.Id }})
    },
    handleReport(row) {
      if (row.Status < 4) return this.$message.error('评测标注未完成')
      var sIdList = ''
      if (row.Id) {
        sIdList = sIdList + row.Id
        const params = {
          STaskIdList: sIdList,
          ReportKey: reportKey,
          VersionId: version
        }
        sessionStorage.setItem('TASKDATA', JSON.stringify(params))
        this.$router.push({ path: '/taskList/list/report', query: {}})
      } else {
        if (this.multipleSelection.length === 0) {
          return
        }
        var version = this.multipleSelection[0].VersionId
        var reportKey = this.multipleSelection[0].ReportKey
        var isOK = true
        this.multipleSelection.forEach(item => {
          sIdList = sIdList + item.Id + ','
          if (version !== item.VersionId || reportKey !== item.VersionId) {
            isOK = false
          }
        })
        if (!isOK) {
          return
        }
        sIdList = sIdList.slice(0, sIdList.length - 1)
        const params = {
          STaskIdList: sIdList,
          ReportKey: reportKey,
          VersionId: version
        }
        sessionStorage.setItem('TASKDATA', JSON.stringify(params))
        this.$router.push({ path: '/taskList/list/report', query: {}})
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .app {
    &-container {
      margin: 30px;
    }
    &-text {
      font-size: 30px;
      line-height: 46px;
    }
  }
  .search {
    width: 30%;
    float: right;
  }
  .el-row {
    margin-bottom: 20px;
    &:last-child {
      margin-bottom: 0;
    }
  }
  .el-col {
    border-radius: 4px;
  }
  .bg-purple-dark {
    background: #99a9bf;
  }
  .bg-purple {
    background: #d3dce6;
  }
  .bg-purple-light {
    background: #e5e9f2;
  }
  .grid-content {
    border-radius: 4px;
    min-height: 36px;
  }
  .row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
  }
</style>
<style lang="scss" scoped>
  .small-select{
    border-color: #ccc;
    color: #666;
    padding: 0 5px;
  }
  .small-buttom{
    width:100%;
    text-align: left;
    padding: 10px 15px;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    &:active {
      border-color: #c7c9cf;
    }
    &:focus {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    &:hover {
      border-color: #c7c9cf;
      background-color: #fff;
    }
  }
  .small-dropdown{
    width:100%;
    text-align: left;
    padding: 5px 20px 5px 0;
    position: relative;
    border: 1px solid #DCDFE6;
    border-radius: 5px;
    white-space: normal;
    min-height: 28px;
    &:active {
      border-color: #c7c9cf;
    }
    &:focus {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    &:hover {
      border-color: #c7c9cf;
      background-color: #fff;
    }
    .dropdown-checked{
      display: inline-block;
      font-size: 12px;
      border: 1px solid #e9e9eb;
      background-color: #f4f4f5;
      border-color: #e9e9eb;
      color: #909399;
      padding: 2px 4px 2px 8px;
      border-radius: 3px;
      height: 24px;
      line-height: 18px;
      margin: 2px 0 2px 6px;
    }
    .dropdown-checked_no{
      color:#bbb;
      // margin: 5px 0 5px 12px;
      padding: 0;
      border:none;
      background: none;
      line-height: 22px;
      margin-left: 10px;
    }
    .delete-dataset{
      background-color: #C0C4CC;
      color: #909399;
      border-radius: 50%;
      font-size: 10px;
      padding: 3px 2px 2px 3px;
      margin-left: 5px;
      transform: scale(0.8);
      &:hover{
        background-color: #909399;
        color: #eee;
      }
    }
  }
   .small-dropdown>span{
    display:block;
    word-break:break-all;
    word-wrap:break-word;
    white-space: normal;
  }
  .small-dropdown_active_icon{
    transform: scale(0);
  }
  .small-dropdown_active{
    // background-color: #e8f4ff;
    color: #46a6ff;
    font-weight: bold;
    .small-dropdown_active_icon{
      transform: scale(1);
    }
  }
  .small-dropdown_item{
    padding: 0px 20px;
    &:hover{
      cursor: pointer;
      background-color: #eee;
    }
  }
</style>
